import router from './router'
import store from './store'
import {
  Message
} from 'element-ui'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import {
  getToken
} from '@/utils/auth'
import {
  isRelogin
} from '@/utils/request'
import request from '@/utils/request'
NProgress.configure({
  showSpinner: false
})

const whiteList = ['/login', '/register', '/UkeyLogin', '/authorizationFunction', '/task/task']
router.beforeEach((to, from, next) => {
  NProgress.start()

  if (getToken()) {
    to.meta.title && store.dispatch('settings/setTitle', to.meta.title)
    console.log(to)
    /* has token*/
    if (to.path === '/login') {
      next({
        path: '/'
      })
      NProgress.done()
    } else {
      if (store.getters.roles.length === 0) {
        isRelogin.show = true
        // 判断当前用户是否已拉取完user_info信息

        store.dispatch('GetInfo').then((res) => {
          sessionStorage.setItem("getInfo", JSON.stringify(res))
          isRelogin.show = false
          store.dispatch('GenerateRoutes').then(accessRoutes => {
            // 根据roles权限生成可访问的路由表
            router.addRoutes(accessRoutes) // 动态添加可访问路由表
            // console.log(router,"00000000000000000")
            next({
              ...to,
              replace: true
            }) // hack方法 确保addRoutes已完成
          })
        }).catch(err => {
          store.dispatch('LogOut').then(() => {
            Message.error(err)
            next({
              path: '/'
            })
          })
        })
      } else {
        //http://localhost/task/task?secret=wgwewqewqwq
        next()
      }
    }
  } else {
    // 没有token
    console.log(whiteList.indexOf(to.path) !== -1, "ksdfjsdklj")
    if ((to.fullPath.indexOf('/task/task') !== -1 && to.fullPath.indexOf('secret') !== -1) ||
      (to.fullPath.indexOf('/task/task') !== -1 && to.fullPath.indexOf('secret') !== -1)) {
      const urlParams = new URLSearchParams(window.location.search);
      const paramValue = urlParams.get('secret');
      console.log(paramValue, "paramValue----");
      store.dispatch('HtaiLogin', paramValue).then((response) => {
        if (response.data.taskId) {
          next({
            path: `/task/task?taskId=${response.data.taskId}`
          })
          NProgress.done()
        }
        // store.dispatch('GetInfo').then((res) => {
        //   sessionStorage.setItem("getInfo", JSON.stringify(res))
        //   isRelogin.show = false
        //   store.dispatch('GenerateRoutes').then(accessRoutes => {
        //     // 根据roles权限生成可访问的路由表
        //     router.addRoutes(accessRoutes) // 动态添加可访问路由表
        //     // console.log(router,"00000000000000000")
        //     next({
        //       ...to,
        //       replace: true
        //     }) // hack方法 确保addRoutes已完成
        //   })
        // }).catch(err => {
        //   store.dispatch('LogOut').then(() => {
        //     Message.error(err)
        //     next({
        //       path: '/'
        //     })
        //   })
        // })
      })
      }
    //农发单点登录。
    else if((to.fullPath.indexOf('ticket=') !== -1) || (to.fullPath.indexOf('v5ticket=') !== -1) ){
          let ticketVal = to.fullPath.substring(to.fullPath.indexOf('ticket='));
          store.dispatch('NFSignLogin', ticketVal).then((response) => {
            let path;
            if(to.fullPath.indexOf('/task/task?v5ticket=') !== -1){
              path = "/task/task";
            }else{
              path = "/login";
            }
            router.push({
              path: path,
              query: { redirect: "/initialization" }
            })
          })
      }

    else if (whiteList.indexOf(to.path) !== -1) {
      // 在免登录白名单，直接进入
      next()
    } else {
      next(`/login?redirect=${to.fullPath}`) // 否则全部重定向到登录页
      NProgress.done()
    }

  }
})

router.afterEach(() => {
  NProgress.done()
})



function GetRequest() {
  const url = location.search; //获取url中"?"符后的字串
  console.log(url, "ksdfjklsdjfkl--------------------------j")
  let theRequest = new Object();
  if (url.indexOf("?") != -1) {
    let str = url.substr(1);
    strs = str.split("&");
    for (let i = 0; i < strs.length; i++) {
      theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
    }
  }
  return theRequest;
}
